package myRuleConfig;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class MyRule extends AbstractLoadBalancerRule {

    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        }
        Server server = null;
        //如果服务为空就重复获取
        while (server == null) {
            if (Thread.interrupted()) {
                return null;
            }
            List<Server> upList = lb.getReachableServers();//获取存活的服务
            List<Server> allList = lb.getAllServers();//获取全部服务

            int serverCount = allList.size();
            if (serverCount == 0) {  //判断是否有可用服务
                return null;
            }
            /*================下面是获取服务的算法核心==========*/
            //随机获取....只要你修改index值,就是修改了算法
            //所以我们可以写自己的算法去修改index值即可
            int index = chooseRandomInt(serverCount);
            System.out.println("当前服务是:"+index);
            /*====================end=========================*/
            
            //获取服务并判断是否为空/可用
            server = upList.get(index);
            if (server == null) {
                Thread.yield();
                continue;
            }

            if (server.isAlive()) {
                return (server);
            }
            // Shouldn't actually happen.. but must be transient or a bug.
            server = null;
            Thread.yield();
        }
        return server;
    }
    
    /**
     * 获取随机数方法
     * @param serverCount
     * @return
     */
    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

	@Override
	public Server choose(Object key) {
		return choose(getLoadBalancer(), key);
	}

	@Override
	public void initWithNiwsConfig(IClientConfig clientConfig) {
		// TODO Auto-generated method stub
	}
}
